package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-data-hub/cache"
	"novel-data-hub/models"
	"strconv"
	"time"
)

func CarDataList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
		       SELECT
			  car_data.id as DataId,
			  new_cars.car_name as CarName,
			  new_cars.car_type as CarType,
			  new_cars.car_code as CarCode,
			  car_data.data_name as DataName,
			  car_data.data_content as DataContent,
			  car_data.data_num as DataNum
			FROM
			  new_cars
			  LEFT JOIN car_data ON car_data.new_car_id = new_cars.id
			WHERE
			  car_data.id = 1
	*/
	var list []models.CarDataList
	redis_key := "car_data_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("new_cars").
			Select("car_data.id as DataId",
				"new_cars.car_name as CarName",
				"new_cars.car_type as CarType",
				"new_cars.car_code as CarCode",
				"car_data.data_name as DataName",
				"car_data.data_content as DataContent",
				"car_data.data_num as DataNum",
			).
			Joins("LEFT JOIN car_data ON car_data.new_car_id = new_cars.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	models.DB.Model(&models.CarData{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"count": count,
	})
	return
}

func CarDataDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.CarDataList
	redis_key := "car_data_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("new_cars").
			Select("car_data.id as DataId",
				"new_cars.car_name as CarName",
				"new_cars.car_type as CarType",
				"new_cars.car_code as CarCode",
				"car_data.data_name as DataName",
				"car_data.data_content as DataContent",
				"car_data.data_num as DataNum",
			).
			Joins("LEFT JOIN car_data ON car_data.new_car_id = new_cars.id").
			Where("car_data.id = ?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}
